package com.samehope.ar.service.impl;

import com.samehope.ar.constant.DeviceStatusEnum;
import com.samehope.ar.dto.DeviceBindParam;
import com.samehope.ar.entity.Device;
import com.samehope.ar.mapper.DeviceMapper;
import com.samehope.ar.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.samehope.ar.util.RedisUtil;
import com.samehope.ar.util.SessionUtil;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.time.LocalDateTime;

/**
 * <p>
 * 设备 服务实现类
 * </p>
 *
 * @author ZhangLuo
 * @since 2019-12-31
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {

    private final String BIND_PRE = "bqc";

    /**
     * 绑定设备
     * @param param
     */
    @Override
    public void bindDevice(DeviceBindParam param) {
        String srcCode = RedisUtil.get(MessageFormat.format("{0}:{1}", BIND_PRE, SessionUtil.getCompanyId()));
        if (!param.getCode().equals(srcCode)) {
            throw new IllegalArgumentException("绑定校验码不存在或者已过期");
        }

        if (SessionUtil.getDeviceId() != null) {
            throw new IllegalArgumentException("已被绑定的设备, 无法再次绑定");
        }

        Device device = new Device();
        device.setDeviceMac(SessionUtil.getDeviceMac());
        device.setDeviceName(param.getDeviceName());
        device.setCompanyId(SessionUtil.getCompanyId());
        device.setDeviceStatus(DeviceStatusEnum.NOT_ACTIVE.getCode());
        device.setCreateBy(param.getCreateBy());
        device.setCreateDate(LocalDateTime.now());
        this.save(device);
    }

    /**
     * 根据识别码查找设备
     * @param deviceMac
     * @return
     */
    @Override
    public Device findByDeviceMac(String deviceMac) {
        return this.baseMapper.findByDeviceMac(deviceMac);
    }
}
